package com.yssoft.datasource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * @author 鲁菊平
 * @time 2025/11/05 下午 13:52
 * @ 监管企业管理 设置数据源
 */
public class DataSourceContextHolder {
    private static Logger logger = LoggerFactory.getLogger(DataSourceContextHolder.class);
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

    // 定义常量
    public static final String MYSQL = "mysql";
    public static final String ORACLE = "oracle";

    /**
     * 设置数据源
     *
     * @param dataSource
     */
    public static void setDataSource(String dataSource) {
        contextHolder.set(dataSource);
        try {
            // 将数据源绑定到事务管理器
            if (TransactionSynchronizationManager.hasResource(DataSourceContextHolder.class)) {
                Object currentDataSource = TransactionSynchronizationManager.getResource(DataSourceContextHolder.class);
                if (!dataSource.equals(currentDataSource)) {
                    // 数据源发生变化，重新绑定
                    TransactionSynchronizationManager.unbindResource(DataSourceContextHolder.class);
                    TransactionSynchronizationManager.bindResource(DataSourceContextHolder.class, dataSource);
                }
            } else {
                // 首次绑定事务数据源
                TransactionSynchronizationManager.bindResource(DataSourceContextHolder.class, dataSource);
            }
        } catch (IllegalStateException e) {
            logger.error("设置事务数据源时出现异常: " + e.getMessage());
        }
    }

    public static String getDataSource() {
        String dataSource = contextHolder.get();
        if (dataSource == null) {
            // 从事务管理器中获取数据源
            try {
                if (TransactionSynchronizationManager.hasResource(DataSourceContextHolder.class)) {
                    Object resource = TransactionSynchronizationManager.getResource(DataSourceContextHolder.class);
                    if (resource != null) {
                        dataSource = resource.toString();
                        // 同步到 ThreadLocal
                        contextHolder.set(dataSource);
                    }
                }
            } catch (IllegalStateException e) {
                logger.error("从事务管理器获取数据源时异常: " + e.getMessage());
            }
        }
        // 如果仍然为 null，使用默认数据源
        if (dataSource == null) {
            dataSource = MYSQL;
        }
        return dataSource;
    }

    /**
     * 从事务管理器中清除数据源
     */
    public static void clearDataSource() {
        // 清理 ThreadLocal
        contextHolder.remove();
        // 安全地清理事务管理器中的绑定
        try {
            if (TransactionSynchronizationManager.hasResource(DataSourceContextHolder.class)) {
                TransactionSynchronizationManager.unbindResource(DataSourceContextHolder.class);
            } else {
                logger.info("事务中无数据源绑定，无需清理");
            }
        } catch (IllegalStateException e) {
            logger.error("清理事务数据源时出现异常: " + e.getMessage());
        }
        logger.info("数据源清理完成");
    }
}